import React, { Component, Fragment } from 'react'
import PropTypes from 'prop-types'
import Loadable from 'react-loadable'
import { Layout, Form, message } from 'antd'
import { Router, Route, Switch, Redirect } from 'react-router-dom'
import CreateHistory from 'history/createBrowserHistory'
import { connect } from 'react-redux'

import NProgress from 'components/common/nprogress'
import CommonCom from 'components/common'
import GlobalHeader from 'components/common/globalHeader'
import Dashboard from 'components/common/dashboard'
import BreadCrumb from 'components/common/breadCrumb'
import UserEditModal from './com/userEditModal'

// eslint-disable-next-line no-unused-vars
import { routes, menu } from '../routes'
import style from './app.css'
import { countMenu, checkPermission } from '../utils/utils'

const { Header, Content } = Layout

const history = new CreateHistory()

const Loading = () => {
  const { pathname } = location

  if (!/\/scenes\/edit/.test(pathname) && !/\/scenes\/list/.test(pathname) && !/\/scenes\/details/.test(pathname)) {
    localStorage.getItem('scenesPageNo') && localStorage.removeItem('scenesPageNo')
    localStorage.getItem('scenesPageSize') && localStorage.removeItem('scenesPageSize')
  }

  // 当点击跳转的时候此时会先执行当前loading之后才会执行页面的componentWillMount
  NProgress.start()
  return <div />
}
const createComponent = (
  item,
  historyProps,
  router,
  deleteLogout,
  menuData,
  handleEdit
) => {
  const LoadableBar = Loadable({
    loader: async () => {
      try {
        return await require(`${item.page}`)
      } catch (error) {
        console.log(error)
      }
    },
    loading: Loading,
    render (loaded, params) {
      NProgress.done()
      let Component = loaded.default
      return <Component {...params} config={item} />
    }
  })

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {
        history.location.pathname !== '/login' ? <Layout style={{ marginLeft: 200 }} id='content-layout'>
          <Header style={{ background: '#fff', padding: 0 }}>
            <GlobalHeader
              deleteLogout={deleteLogout}
              router={router}
              handleEdit={handleEdit}
            />
          </Header>
          <BreadCrumb current={item} />
          <Content style={{ backgroundColor: '#F6F7FA' }}>
            <div className={style['content-container']}>
              <LoadableBar {...historyProps} router={router} />
            </div>
          </Content>
        </Layout> : <Content style={{ backgroundColor: '#F6F7FA' }}>
          <div className={style['content-container']}>
            <LoadableBar {...historyProps} router={router} />
          </div>
        </Content>
      }
    </Layout>
  )
}

class AppForm extends Component {
  static propTypes = {
    deleteLogout: PropTypes.func,
    auth: PropTypes.array,
    getAuthCode: PropTypes.func
  };
  constructor (props) {
    super(props)
    this.state = {
      menuData: [],
      showModal: false
    }
    this.handleEdit = this.handleEdit.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleOk = this.handleOk.bind(this)
  }

  componentDidMount () {
    this.filter()
    const token = localStorage.getItem('token')
    if (token) {
      this.props.getAuthCode()
    }
  }

  filter () {
    this.setState({
      menuData: JSON.parse(window.localStorage.getItem('power')) || []
    })
  }

  handleEdit () {
    const userId = localStorage.getItem('userId')
    if (userId) {
      this.props.getStaffDetail({
        userId
      })
      setTimeout(() => {
        this.setState({
          showModal: true
        })
      }, 50)
    } else {
      message.warning('请重新登陆')
      setTimeout(() => {
        localStorage.removeItem('token')
        localStorage.removeItem('nickname')
        location.href = '/login'
      }, 500)
    }
  }

  handleCancel () {
    this.setState({
      showModal: false
    })
  }

  handleOk (value) {
    this.setState({
      showModal: false
    })
    this.props.editUserInfo(value)
  }

  render () {
    const { auth, staffDetail = {} } = this.props
    // 过滤权限
    const countRoutes = routes.filter(item => {
      return !item.code || (item.code && checkPermission(item.code, auth))
    })
    const newMenu = countMenu(countRoutes)
    // TODO 权限管理
    return (
      <>
        <CommonCom />
        <Fragment>
          {
            history.location.pathname !== '/login' && <Dashboard router={history} menus={newMenu} />
          }
          <Router history={history}>
            <Switch>
              <Route
                path='/'
                className={style['ere']}
                exact
                render={() => <Redirect to='/home/index' />}
              />
              {routes
                .filter((item) => (item.path !== '/' && !item.hideInRoute))
                .map((item, i) => {
                  return (
                    <Route
                      breadcrumbName={item.name}
                      key={i}
                      {...item.option}
                      path={item.path}
                      component={(historyProps) => {
                        return createComponent(
                          item,
                          historyProps,
                          history,
                          this.props.deleteLogout,
                          this.state.menuData,
                          this.handleEdit
                        )
                      }}
                    />
                  )
                })}
            </Switch>
          </Router>
        </Fragment>
        <UserEditModal onOk={this.handleOk} onCancel={this.handleCancel} staffDetail={staffDetail} showModal={this.state.showModal} />
      </>
    )
  }
}

const mapState = (state) => ({
  auth: state.common.auth,
  staffInfo: state.setup.staffInfo,
  staffDetail: state.setup.staffDetail
})

const mapDispatch = (dispatch) => ({
  deleteLogout: dispatch.common.deleteLogout,
  getAuthCode: dispatch.common.getAuthCode,
  editUserInfo: dispatch.setup.editUserInfo,
  getStaffDetail: dispatch.setup.getStaffDetail
})

const App = Form.create()(AppForm)

export default connect(mapState, mapDispatch)(App)
